
//console.log('Crontab Run JS.[background]..');

/**
 * 初始化数据库
 * **
 */
var db = openDatabase("crontab", "1.0", "Crontab Database", 2000000);
if (!db) {
	console.log('连接数据库失败');
} else {
	console.log("连接数据库成功");
}

/**
 * 初始化数据表相关
 * **
 */
function initDatabase(){
	
	/**
	 * 初始化表结构
	 * **
	 */
	db.transaction(function(tx){
		tx.executeSql("CREATE TABLE IF NOT EXISTS tasks (id INTEGER PRIMARY KEY AUTOINCREMENT,name VARCHAR(250),time BIGINT,tips TEXT)", [], function(tx, data){
			console.log('数据表[tasks]创建成功', tx, data);
		}, function(tx, data){
			console.log('数据表[tasks]创建失败', tx, data);
		});
	});

	/**
	 * 查询任务列表
	 * **
	 */
	db.transaction(function(tx){
		tx.executeSql("SELECT * FROM tasks", [], function(tx, data){
			console.log('查询表[tasks]数据成功', tx, data);
			
		}, function(tx, data){
			console.log('查询表[tasks]数据失败', tx, data);
		});
	});
	
}

/**
 * 初始化测试数据
 * **
 */
function initDemoData(){
	
	/**
	 * 插入一条记录
	 * **
	 */
	db.transaction(function(tx){
		var name = 'task_' + Math.random();
		var time = Date.now() + (60*1000);
		var tips = '哈哈哈哈哈哈 ' + new Date().toString();
		tx.executeSql("INSERT INTO tasks (name,time,tips) values(?, ?, ?)", [name, time, tips], function(tx, data){
			console.log('插入表[tasks]数据成功', tx, data);
		}, function(tx, data){
			console.log('插入表[tasks]数据失败', tx, data);
		});
	});
	
}


/**
 * 获取数据列表
 * **
 */
function getAllDataList(callback){
	
	/**
	 * 查询数据
	 * **
	 */
	db.transaction(function(tx){
		tx.executeSql("SELECT * FROM tasks", [], function(tx, data){
			console.log('查询表[tasks]数据成功', tx, data);
			callback.apply(tx, [data]);
		}, function(tx, data){
			console.log('查询表[tasks]数据失败', tx, data);
			callback.apply(tx, [data]);
		});
	});
	
}



/****************************************************************************************************************/
/*								chrome.storage																	*/
/****************************************************************************************************************/


/**
 * 添加一个新任务
 * **
 */
function newTask(name, data, alarmInfo, callback){
	console.log('新增一个定时任务', name, alarmInfo);
	chrome.storage.local.get(['tasks'], function(res){
		console.log('获取本地缓存数据[tasks]', res);
		var tasks = {};
		if(res.tasks && typeof res.tasks == 'object'){
			tasks = res.tasks;
		}
		tasks[name] = {
			config: data,
			alarm: alarmInfo,
			callback: callback
		};
		console.log('要保存的数据', tasks);
		chrome.storage.local.set({
			tasks: tasks
		}, function(){
			console.log('数据保存成功');
		});
	});
	chrome.alarms.create(name, alarmInfo);
}


/**
 * 查询所有任务列表
 * **
 */
function queryTask(callback){
	console.log('开始查询所有任务列表');
	chrome.storage.local.get(['tasks'], function(res){
		var tasks = {};
		if(res.tasks && typeof res.tasks == 'object'){
			tasks = res.tasks;
		}
		console.log('查询所有任务,准备调用回调[callback]', tasks);
		callback.apply(res, [tasks]);
	});
}


/**
 * 清除所有任务
 * **
 */
function clearTask(){
	console.log('清除所有任务');
	chrome.storage.local.clear();
	chrome.alarms.clearAll();
}


/**
 * 一加载插件，设置默认数据
 * **
 */
chrome.runtime.onInstalled.addListener(reason => {
	//initDatabase();
	//initDemoData();
});


var taskRunCallback = null;

/**
 * 监听定时执行事件
 * **
 */
chrome.alarms.onAlarm.addListener(alarm => {
	
	console.log('监听到定时任务事件', alarm);
	
	chrome.storage.local.get(['tasks','notifications'], res => {
		if(res.tasks && typeof res.tasks == 'object'){
			var data = res.tasks[alarm.name] || false;
			if(data){
				var config = data.config || {};
				config.type = config.type || 'basic';
				config.iconUrl = config.iconUrl || 'images/icon.png';
				config.title = config.title || '您有一个新的提醒';
				config.message = config.message || '提醒内容';
				config.contextMessage = config.contextMessage || 'Crontab';
				//config.requireInteraction = config.requireInteraction || true;
				
				chrome.notifications.create(alarm.name, config);
				
				var notifications = {};
				if(res.notifications && typeof res.notifications == 'object'){
					notifications = res.notifications;
				}
				notifications[alarm.name] = data;
				
				res.tasks[alarm.name] = false;
				delete res.tasks[alarm.name];
				chrome.storage.local.set({
					tasks: res.tasks,
					notifications: notifications
				}, function(){
					console.log('更新本地数据保存成功');
					if(typeof taskRunCallback == 'function'){
						taskRunCallback.apply(this, []);
					}
				});
			}
		}
	});
	
});


/**
 * 监听Chrome通知点击事件
 * **
 */
chrome.notifications.onClicked.addListener(function(notificationId){
	
	console.log('监听到通知点击事件', notificationId);
	
	chrome.storage.local.get(['notifications'], res => {
		if(res.notifications && typeof res.notifications == 'object'){
			var data = res.notifications[notificationId] || false;
			if(data){
				
				console.log('成功获取到通知事件相关数据', data);
				
				if(typeof data.callback == 'string' && data.callback != ''){
					chrome.tabs.create({url: data.callback});
				}
				
				if(typeof data.callback == 'function'){
					data.callback.apply(this, [data, notificationId]);
				}
				
				res.notifications[notificationId] = false;
				delete res.notifications[notificationId];
				chrome.storage.local.set({
					notifications: res.notifications
				}, function(){
					console.log('更新通知数据缓存成功');
				});
			}
		}
	});
	
});
